package com.dongman.scrapy;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doPost(String url,String jsonstr,String charset){
        logger.info("请求的地址：" + url);
        logger.info("请求的参数：" + jsonstr);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int times = 0;
        while (times < 10) {
            HttpClient httpClient;
            HttpPost httpPost;
            String result;
            try{
                httpClient = new SSLClient();
                httpPost = new HttpPost(url);
                httpPost.addHeader("Content-Type", "application/json");
                StringEntity se = new StringEntity(jsonstr);
                se.setContentType("text/json");
                se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
                httpPost.setEntity(se);
                HttpResponse response = httpClient.execute(httpPost);
                if(response != null){
                    HttpEntity resEntity = response.getEntity();
                    if(resEntity != null){
                        result = EntityUtils.toString(resEntity,charset);
                        logger.info(result);
                        return result;
                    }
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
            times = times + 1;
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
//        String page = "2";
//        String limit = "10";
//        String jsonStr = "{\"projectName\":\"\",\"certNo\":\"\",\"developer\":\"\"}";
//        JSONObject params = new JSONObject();
//        params.put("page", page);
//        params.put("limit", limit);
//        params.put("jsonStr", jsonStr);
//        String url  = "https://yc.nxzhzj.cn/estateTradeR01/portals/query!listSalePermitProject";
        String url = "https://back.getmogic.com/creativeSaaS/auth/v1/tenantAccessToken/internal";
        JSONObject params = new JSONObject();
        params.put("appId", "mogic-pepsi");
        params.put("appSecret", "54b0b57220eceafc2d9b2f1ff705756b");
        doPost(url, params.toJSONString(), "utf-8");
    }
}
